package com.baidu.ryujin.accessbilitytest

import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.GestureDescription
import android.accessibilityservice.GestureDescription.StrokeDescription
import android.content.Context
import android.graphics.Path
import android.nfc.Tag
import android.os.Handler
import android.util.DisplayMetrics
import android.util.Log
import android.view.WindowManager
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityNodeInfo


/**
 * @author ryujin
 * @time 2020/7/25 23:30
 *
 */
class DouyinService : AccessibilityService() {
    companion object {
        val TAG: String = DouyinService.javaClass.simpleName
    }

    private var lastTime = 0L
    override fun onInterrupt() {
        TODO("Not yet implemented")
    }


    override fun onAccessibilityEvent(event: AccessibilityEvent?) {
        if (System.currentTimeMillis() - lastTime > 2000) {
            performGlobalSelect("com.ss.android.ugc.aweme:id/b1m")
//            performGlobalClick("com.ss.android.ugc.aweme:id/bhk")
            Handler().postDelayed({ mainActivityToUp() },2000)
            lastTime = System.currentTimeMillis()
        }
        //显示更新提示框
//        if (event?.className.toString() == "com.ss.android.ugc.aweme.update.j") {
//            performGlobalClick("com.ss.android.ugc.aweme:id/cev");//点击"以后再说"
//        }
//        //跳过广告
//        if (event?.className.toString().equals("com.ss.android.ugc.aweme.splash.SplashActivity")) {
//            performGlobalClick("com.ss.android.ugc.aweme:id/ce2");//点击"跳过广告"
//        }
        //点赞
        val userNames =
            rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.ss.android.ugc.aweme:id/title")
        rootInActiveWindow.recycle()
//        for (userName in userNames) {
//            Log.i(TAG, "用户名:" + userName?.text?.toString() + "")
//        }
        if ("android.widget.ImageView" == event?.className.toString()) {
            Log.i(TAG, "用户名:" + getTextById("com.ss.android.ugc.aweme:id/title"));
            Log.i(TAG, "文本信息:" + getTextById("com.ss.android.ugc.aweme:id/a92"));
        }
    }

    /**
     * 根据ID点击某个视图
     */
    private fun performGlobalClick(id: String?) {
        val list = rootInActiveWindow.findAccessibilityNodeInfosByViewId(id)
        rootInActiveWindow.recycle()
        for (item in list) {
            item.performAction(AccessibilityNodeInfo.ACTION_CLICK)
        }
    }

    /**
     * 根据ID点击某个视图
     */
    private fun performGlobalSelect(id: String?) {
        val list = rootInActiveWindow.findAccessibilityNodeInfosByViewId(id)
        rootInActiveWindow.recycle()
        for (item in list) {
            item.performAction(AccessibilityNodeInfo.ACTION_SELECT)
        }
    }

    /**
     * 获取指定ID的文本
     */
    private fun getTextById(id: String): String? {
        val list = rootInActiveWindow.findAccessibilityNodeInfosByViewId(id)
        rootInActiveWindow.recycle()
        for (item in list) {
            return item.text.toString() + ""
        }
        return ""
    }

    /**
     * 判断页面是否有此文本的view
     */
    private fun viewByText(str: String): Boolean {
        val list = rootInActiveWindow.findAccessibilityNodeInfosByText(str)
        rootInActiveWindow.recycle()
        for (item in list) {
            if (str == item.text.toString()) {
                return true
            }
        }
        return false
    }

    //上划主页面
    private fun mainActivityToUp() {
        val wm: WindowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val dm = DisplayMetrics()
        wm.defaultDisplay.getMetrics(dm);
        val width = dm.widthPixels        // 屏幕宽度（像素）
        val height = dm.heightPixels     // 屏幕高度（像素）
        val density = dm.density         // 屏幕密度（0.75 / 1.0 / 1.5）
        val screenWidth = (width / density)  // 屏幕宽度(dp)
        val screenHeight = (height / density)// 屏幕高度(dp)
        val path = Path()
        path.moveTo((width/2).toFloat(), (height/2).toFloat())
        path.lineTo((width/2).toFloat(), 0F)
        val builder = GestureDescription.Builder()
        builder.addStroke(StrokeDescription(path, 100L, 500L))
        val gesture = builder.build()
        dispatchGesture(gesture, object : GestureResultCallback() {
            override fun onCompleted(gestureDescription: GestureDescription) {
                super.onCompleted(gestureDescription)
                Log.e(TAG, "onCompleted: 主页上滑.")
            }

            override fun onCancelled(gestureDescription: GestureDescription) {
                super.onCancelled(gestureDescription)
            }
        }, null)
    }

}